<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Model\AdminUser;
use App\Model\AdminRole;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
	public function index(){
		$users = AdminUser::paginate(10);
        return view('admin.user.index', compact('users'));
	}

	public function create(){
		return view('/admin/user/add');
	}

	public function store(Request $request){
		 $this->validate(request(), [
            'name' => 'required|min:3',
            'password' => 'required'
        ]);

        $name = $request->input('name');
        $password = bcrypt($request->input('password'));
        $adminUser = new AdminUser();
        $adminUser->email = $name;
        $adminUser->password = $password;
        $adminUser->created_at = time();
        $adminUser->save();
        return redirect('/admin/users');
	}

    /**
     * 角色管理页面
     */
    public function role(AdminUser $user){
        $roles = AdminRole::all();
        $myRoles = $user->roles;
        return view('admin/user/role',compact('user','myRoles','roles'));
    }

    /*
     * 保存权限
     */
    public function storeRole(AdminUser $user)
    {
        $this->validate(request(),[
            'roles' => 'required|array'
        ]);

        $roles = AdminRole::find(request('roles'));
        $myRoles = $user->roles;

        // 对已经有的权限
        $addRoles = $roles->diff($myRoles);
        foreach ($addRoles as $role) {
            $user->roles()->save($role);
        }

        $deleteRoles = $myRoles->diff($roles);
        foreach ($deleteRoles as $role) {
            $user->deleteRole($role);
        }
        return back();
    }
}
